const { SimpleData, SuccessData } = require('../common/returnDataFormat');
const { setToken } = require('../utils/token');
const User = require('../model/user');
const Topic = require('../model/topic');
const sequelize = require('sequelize');
const Comment = require('../model/comment');
// 通过用户名查询用户信息函数
module.exports.selectUserByName = async (username) => {
  const result = await User.findOne({
    where: {
      username,
    },
    include: [
      {
        model: Topic,
        as: 'topic',
      },
    ],
  });
  if (result) {
    return SuccessData(result.get({ plain: true }));
  } else {
    return SimpleData(false, '用户不存在');
  }
};
//根据id查询用户
module.exports.findOneUser = async (user_id) => {
  const result = (
    await User.findOne({
      where: {
        user_id,
      },
      include: [
        {
          model: Topic,
          as: 'topic',
          include: [
            {
              model: Comment,
              attributes: ['id'],
            },
          ],
        },
      ],
      attributes: {
        exclude: ['created_time', 'update_time'],
      },
    })
  ).get({ plain: true });
  return SuccessData(result);
};
// 添加用户
module.exports.addUser = async (params) => {
  const user = await this.selectUserByName(params.username);
  if (user.success) {
    return {
      msg: '用户已存在',
    };
  } else {
    // const result = await pool(SQL.AddUser, params)
    const result = (await User.create(params)).get({ plain: true });
    if (result) return SimpleData(200, '用户添加成功');
  }
};

//登录用户
module.exports.userLogin = async (params) => {
  let result = await User.findOne({
    where: { ...params },
    attributes: {
      // exclude: ['password'],
    },
    through: {
      attribute: ['created_time', 'updated_time'],
    },
    include: [
      {
        model: Topic,
        attributes: ['topic_id'],
        as: 'topic',
      },
    ],
  });
  if (result) {
    result = result.get({ plain: true });
    const token = await setToken(
      result.username,
      result.user_id,
      result.user_level,
      result.state
    );
    result.topic = result.topic.length;
    return SuccessData({
      ...result,
      token,
    });
  } else {
    return SimpleData(500, '用户名或密码存在错误');
  }
};

//验证用户是否已经存在
module.exports.validateUser = async (username) => {
  const cantUpdate = await User.findOne({
    where: {
      username,
    },
    raw: true,
  });
  if (cantUpdate) {
    return SimpleData(500, '该用户名已存在');
  } else {
    return SimpleData(200, '用户名不存在');
  }
};

//修改用户
module.exports.modifyUser = async (params) => {
  const result = await User.update(
    { ...params[0] },
    {
      where: {
        user_id: params[1],
      },
    }
  );
  if (result[0]) {
    return SimpleData(200, '修改用户成功');
  } else {
    return SimpleData(500, '用户修改失败');
  }
};

// 删除用户
module.exports.deleteUser = async (userId) => {
  const result = await User.destroy({
    where: {
      user_id: userId,
    },
  });
  if (result) {
    return SimpleData(200, '删除用户成功');
  } else {
    return SimpleData(500, '删除用户失败');
  }
};

//分页查询用户
module.exports.pagingUsers = async ({ offset, limit, username }) => {
  if (limit) {
    offset = (offset - 1) * limit;
  } else {
    offset = 0;
  }
  const result = await User.findAndCountAll({
    where: {
      username: {
        [sequelize.Op.like]: '%' + username + '%',
      },
    },
    offset,
    limit,
  });
  if (result) {
    return result;
  } else {
    return SimpleData(500, '获取用户列表失败');
  }
};
